<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>JVM系列-第5章-堆 | 风祈的时光录</title><meta name="keywords" content="JVM，虚拟机。"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JVM系列-第5章-堆。">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM系列-第5章-堆">
<meta property="og:url" content="https://imlql.cn/post/50ac3a1c.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="JVM系列-第5章-堆。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png">
<meta property="article:published_time" content="2020-11-11T12:38:42.000Z">
<meta property="article:modified_time" content="2022-07-24T11:02:09.800Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="JVM">
<meta property="article:tag" content="虚拟机">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/50ac3a1c"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JVM系列-第5章-堆',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:02:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JVM系列-第5章-堆</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-11-11T12:38:42.000Z" title="发表于 2020-11-11 20:38:42">2020-11-11</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:02:09.800Z" title="更新于 2022-07-24 19:02:09">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/JVM/">JVM</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/JVM/1-%E5%86%85%E5%AD%98%E4%B8%8E%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AF%87/">1.内存与垃圾回收篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">10.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>36分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="堆"><a href="#堆" class="headerlink" title="堆"></a>堆</h1><h2 id="堆的核心概述"><a href="#堆的核心概述" class="headerlink" title="堆的核心概述"></a>堆的核心概述</h2><h3 id="堆与进程"><a href="#堆与进程" class="headerlink" title="堆与进程"></a>堆与进程</h3><ol>
<li> 堆针对一个JVM进程来说是唯一的。也就是<strong>一个进程只有一个JVM实例</strong>，一个JVM实例中就有一个运行时数据区，一个运行时数据区只有一个堆和一个方法区。</li>
<li> 但是<strong>进程包含多个线程，他们是共享同一堆空间的</strong>。</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0001.png">



<ol>
<li><p> 一个JVM实例只存在一个堆内存，堆也是Java内存管理的核心区域。</p>
</li>
<li><p> Java堆区在JVM启动的时候即被创建，其空间大小也就确定了，堆是JVM管理的最大一块内存空间，并且堆内存的大小是可以调节的。</p>
</li>
<li><p> 《Java虚拟机规范》规定，堆可以处于物理上不连续的内存空间中，但在逻辑上它应该被视为连续的。</p>
</li>
<li><p> 所有的线程共享Java堆，在这里还可以划分线程私有的缓冲区（Thread Local Allocation Buffer，<strong>TLAB</strong>）。</p>
</li>
<li><p>《Java虚拟机规范》中对Java堆的描述是：<strong>所有的对象实例以及数组都应当在运行时分配在堆上</strong>。（The heap is the run-time data area from which memory for all class instances and arrays is allocated）</p>
<ul>
<li>从实际使用角度看：“几乎”所有的对象实例都在堆分配内存，但并非全部。因为还有一些对象是在栈上分配的（逃逸分析，标量替换）</li>
</ul>
</li>
<li><p> 数组和对象可能永远不会存储在栈上（<strong>不一定</strong>），因为栈帧中保存引用，这个引用指向对象或者数组在堆中的位置。</p>
</li>
<li><p>在方法结束后，堆中的对象不会马上被移除，仅仅在垃圾收集的时候才会被移除。</p>
<ul>
<li>  也就是触发了GC的时候，才会进行回收</li>
<li>  如果堆中对象马上被回收，那么用户线程就会收到影响，因为有stop the word</li>
</ul>
</li>
<li><p> 堆，是GC（Garbage Collection，垃圾收集器）执行垃圾回收的重点区域。</p>
</li>
</ol>
<blockquote>
<p>随着JVM的迭代升级，原来一些绝对的事情，在后续版本中也开始有了特例，变的不再那么绝对。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleHeap</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> id;<span class="comment">//属性、成员变量</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SimpleHeap</span><span class="params">(<span class="keyword">int</span> id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">show</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;My ID is &quot;</span> + id);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SimpleHeap sl = <span class="keyword">new</span> SimpleHeap(<span class="number">1</span>);</span><br><span class="line">        SimpleHeap s2 = <span class="keyword">new</span> SimpleHeap(<span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span>[] arr = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line">        Object[] arr1 = <span class="keyword">new</span> Object[<span class="number">10</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0002.png">



<h3 id="堆内存细分"><a href="#堆内存细分" class="headerlink" title="堆内存细分"></a>堆内存细分</h3><p>现代垃圾收集器大部分都基于分代收集理论设计，堆空间细分为：</p>
<ol>
<li>Java7 及之前堆内存逻辑上分为三部分：新生区+养老区+永久区<ul>
<li>Young Generation Space    新生区      Young/New<ul>
<li>  又被划分为Eden区和Survivor区</li>
</ul>
</li>
<li>  Old generation space    养老区           Old/Tenure</li>
<li>  Permanent Space   永久区                   Perm</li>
</ul>
</li>
<li>Java 8及之后堆内存逻辑上分为三部分：新生区+养老区+元空间<ul>
<li>  Young Generation Space 新生区，又被划分为Eden区和Survivor区</li>
<li>  Old generation space 养老区</li>
<li>  Meta Space 元空间 Meta</li>
</ul>
</li>
</ol>
<p>约定：新生区 &lt;–&gt; 新生代 &lt;–&gt; 年轻代 、 养老区 &lt;–&gt; 老年区 &lt;–&gt; 老年代、 永久区 &lt;–&gt; 永久代</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0003.png">



<ol start="2">
<li> 堆空间内部结构，JDK1.8之前从永久代 替换成 元空间</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0004.png">



<h2 id="JVisualVM可视化查看堆内存"><a href="#JVisualVM可视化查看堆内存" class="headerlink" title="JVisualVM可视化查看堆内存"></a>JVisualVM可视化查看堆内存</h2><p>运行下面代码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeapDemo</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;start...&quot;</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.MINUTES.sleep(<span class="number">30</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;end...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>1、双击jdk目录下的这个文件</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0005.png">



<p>2、工具 -&gt; 插件 -&gt; 安装Visual GC插件</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0006.png">

<p>3、运行上面的代码</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0007.png">



<h2 id="设置堆内存大小与-OOM"><a href="#设置堆内存大小与-OOM" class="headerlink" title="设置堆内存大小与 OOM"></a>设置堆内存大小与 OOM</h2><h3 id="设置堆内存"><a href="#设置堆内存" class="headerlink" title="设置堆内存"></a>设置堆内存</h3><ol>
<li>Java堆区用于存储Java对象实例，那么堆的大小在JVM启动时就已经设定好了，大家可以通过选项”-Xms”和”-Xmx”来进行设置。<ul>
<li>  <strong>-Xms</strong>用于表示堆区的起始内存，等价于**-XX:InitialHeapSize**</li>
<li>  <strong>-Xmx</strong>则用于表示堆区的最大内存，等价于**-XX:MaxHeapSize**</li>
</ul>
</li>
<li> 一旦堆区中的内存大小超过“-Xmx”所指定的最大内存时，将会抛出OutofMemoryError异常。</li>
<li> 通常会将-Xms和-Xmx两个参数配置相同的值</li>
</ol>
<ul>
<li>原因：假设两个不一样，初始内存小，最大内存大。在运行期间如果堆内存不够用了，会一直扩容直到最大内存。如果内存够用且多了，也会不断的缩容释放。频繁的扩容和释放造成不必要的压力，避免在GC之后调整堆内存给服务器带来压力。</li>
<li>如果两个设置一样的就少了频繁扩容和缩容的步骤。内存不够了就直接报OOM</li>
</ul>
<ol start="4">
<li><p>默认情况下:</p>
<ul>
<li>  初始内存大小：物理电脑内存大小/64</li>
<li>  最大内存大小：物理电脑内存大小/4</li>
</ul>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 1. 设置堆空间大小的参数</span></span><br><span class="line"><span class="comment"> * -Xms 用来设置堆空间（年轻代+老年代）的初始内存大小</span></span><br><span class="line"><span class="comment"> *      -X 是jvm的运行参数</span></span><br><span class="line"><span class="comment"> *      ms 是memory start</span></span><br><span class="line"><span class="comment"> * -Xmx 用来设置堆空间（年轻代+老年代）的最大内存大小</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 2. 默认堆空间的大小</span></span><br><span class="line"><span class="comment"> *    初始内存大小：物理电脑内存大小 / 64</span></span><br><span class="line"><span class="comment"> *             最大内存大小：物理电脑内存大小 / 4</span></span><br><span class="line"><span class="comment"> * 3. 手动设置：-Xms600m -Xmx600m</span></span><br><span class="line"><span class="comment"> *     开发中建议将初始堆内存和最大的堆内存设置成相同的值。</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 4. 查看设置的参数：方式一： jps   /  jstat -gc 进程id</span></span><br><span class="line"><span class="comment"> *                  方式二：-XX:+PrintGCDetails</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeapSpaceInitial</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//返回Java虚拟机中的堆内存总量</span></span><br><span class="line">        <span class="keyword">long</span> initialMemory = Runtime.getRuntime().totalMemory() / <span class="number">1024</span> / <span class="number">1024</span>;</span><br><span class="line">        <span class="comment">//返回Java虚拟机试图使用的最大堆内存量</span></span><br><span class="line">        <span class="keyword">long</span> maxMemory = Runtime.getRuntime().maxMemory() / <span class="number">1024</span> / <span class="number">1024</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;-Xms : &quot;</span> + initialMemory + <span class="string">&quot;M&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;-Xmx : &quot;</span> + maxMemory + <span class="string">&quot;M&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;系统内存大小为：&quot;</span> + initialMemory * <span class="number">64.0</span> / <span class="number">1024</span> + <span class="string">&quot;G&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;系统内存大小为：&quot;</span> + maxMemory * <span class="number">4.0</span> / <span class="number">1024</span> + <span class="string">&quot;G&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">-Xms : 123M</span><br><span class="line">-Xmx : 1794M</span><br><span class="line">系统内存大小为：<span class="number">7.</span>6875G</span><br><span class="line">系统内存大小为：<span class="number">7.</span>0078125G</span><br></pre></td></tr></table></figure>

<p>1、笔者电脑内存大小是8G，不足8G的原因是操作系统自身还占据了一些。</p>
<p>2、两个不一样的原因待会再说</p>
<p>设置下参数再看</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0008.png">

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeapSpaceInitial</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//返回Java虚拟机中的堆内存总量</span></span><br><span class="line">        <span class="keyword">long</span> initialMemory = Runtime.getRuntime().totalMemory() / <span class="number">1024</span> / <span class="number">1024</span>;</span><br><span class="line">        <span class="comment">//返回Java虚拟机试图使用的最大堆内存量</span></span><br><span class="line">        <span class="keyword">long</span> maxMemory = Runtime.getRuntime().maxMemory() / <span class="number">1024</span> / <span class="number">1024</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;-Xms : &quot;</span> + initialMemory + <span class="string">&quot;M&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;-Xmx : &quot;</span> + maxMemory + <span class="string">&quot;M&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">-Xms : 575M</span><br><span class="line">-Xmx : 575M</span><br></pre></td></tr></table></figure>

<p>为什么会少25M</p>
<p><strong>方式一： jps   /  jstat -gc 进程id</strong></p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0009.png">

<blockquote>
<p>jps：查看java进程</p>
<p>jstat：查看某进程内存使用情况</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">SOC: S0区总共容量</span><br><span class="line">S1C: S1区总共容量</span><br><span class="line">S0U: S0区使用的量</span><br><span class="line">S1U: S1区使用的量</span><br><span class="line">EC: 伊甸园区总共容量</span><br><span class="line">EU: 伊甸园区使用的量</span><br><span class="line">OC: 老年代总共容量</span><br><span class="line">OU: 老年代使用的量</span><br></pre></td></tr></table></figure>

<p>1、</p>
<p>25600+25600+153600+409600 = 614400K</p>
<p>614400 /1024 = 600M</p>
<p>2、</p>
<p>25600+153600+409600 = 588800K</p>
<p>588800 /1024 = 575M</p>
<p>3、</p>
<p>并非巧合，S0区和S1区两个只有一个能使用，另一个用不了（后面会详解）</p>
<p> <strong>方式二：-XX:+PrintGCDetails</strong></p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0010.png">



<h3 id="OOM"><a href="#OOM" class="headerlink" title="OOM"></a>OOM</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OOMTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ArrayList&lt;Picture&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">while</span>(<span class="keyword">true</span>)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">20</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            list.add(<span class="keyword">new</span> Picture(<span class="keyword">new</span> Random().nextInt(<span class="number">1024</span> * <span class="number">1024</span>)));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Picture</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">byte</span>[] pixels;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Picture</span><span class="params">(<span class="keyword">int</span> length)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.pixels = <span class="keyword">new</span> <span class="keyword">byte</span>[length];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>1、设置虚拟机参数</p>
<p><code>-Xms600m -Xmx600m</code></p>
<p>最终输出结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Exception in thread <span class="string">&quot;main&quot;</span> java.lang.OutOfMemoryError: Java heap space</span><br><span class="line">	at com.atguigu.java.Picture.&lt;init&gt;(OOMTest.java:<span class="number">29</span>)</span><br><span class="line">	at com.atguigu.java.OOMTest.main(OOMTest.java:<span class="number">20</span>)</span><br><span class="line"></span><br><span class="line">Process finished with exit code <span class="number">1</span></span><br></pre></td></tr></table></figure>



<p>2、堆内存变化图</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0011.png">

<p>3、原因：大对象导致堆内存溢出</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0012.png">



<h2 id="年轻代与老年代"><a href="#年轻代与老年代" class="headerlink" title="年轻代与老年代"></a>年轻代与老年代</h2><p>1、存储在JVM中的Java对象可以被划分为两类：</p>
<pre><code>- 一类是生命周期较短的瞬时对象，这类对象的创建和消亡都非常迅速
- 另外一类对象的生命周期却非常长，在某些极端的情况下还能够与JVM的生命周期保持一致
</code></pre>
<p>2、Java堆区进一步细分的话，可以划分为年轻代（YoungGen）和老年代（oldGen）</p>
<p>3、其中年轻代又可以划分为Eden空间、Survivor0空间和Survivor1空间（有时也叫做from区、to区）</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0013.png">

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0014.png">

<ul>
<li><p>配置新生代与老年代在堆结构的占比</p>
<ul>
<li><p>默认**-XX:NewRatio**=2，表示新生代占1，老年代占2，新生代占整个堆的1/3</p>
</li>
<li><p>可以修改**-XX:NewRatio**=4，表示新生代占1，老年代占4，新生代占整个堆的1/5</p>
</li>
</ul>
</li>
</ul>
<ol>
<li><p>在HotSpot中，Eden空间和另外两个survivor空间缺省所占的比例是8 : 1 : 1，</p>
</li>
<li><p>当然开发人员可以通过选项**-XX:SurvivorRatio**调整这个空间比例。比如-XX:SurvivorRatio=8</p>
</li>
<li><p>几乎所有的Java对象都是在Eden区被new出来的。</p>
</li>
<li><p>绝大部分的Java对象的销毁都在新生代进行了（有些大的对象在Eden区无法存储时候，将直接进入老年代），IBM公司的专门研究表明，新生代中80%的对象都是“朝生夕死”的。</p>
</li>
<li><p>可以使用选项”-Xmn”设置新生代最大内存大小，但这个参数一般使用默认值就可以了。</p>
</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0015.png">



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * -Xms600m -Xmx600m</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * -XX:NewRatio ： 设置新生代与老年代的比例。默认值是2.</span></span><br><span class="line"><span class="comment"> * -XX:SurvivorRatio ：设置新生代中Eden区与Survivor区的比例。默认值是8</span></span><br><span class="line"><span class="comment"> * -XX:-UseAdaptiveSizePolicy ：关闭自适应的内存分配策略  （暂时用不到）</span></span><br><span class="line"><span class="comment"> * -Xmn:设置新生代的空间的大小。 （一般不设置）</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> shkstart  shkstart@126.com</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@create</span> 2020  17:23</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EdenSurvivorTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;我只是来打个酱油~&quot;</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="图解对象分配过程"><a href="#图解对象分配过程" class="headerlink" title="图解对象分配过程"></a>图解对象分配过程</h2><p>为新对象分配内存是一件非常严谨和复杂的任务，JVM的设计者们不仅需要考虑内存如何分配、在哪里分配等问题，并且由于内存分配算法与内存回收算法密切相关，所以还需要考虑GC执行完内存回收后是否会在内存空间中产生内存碎片。</p>
<p><strong>具体过程</strong></p>
<ol>
<li> new的对象先放伊甸园区。此区有大小限制。</li>
<li> 当伊甸园的空间填满时，程序又需要创建对象，JVM的垃圾回收器将对伊甸园区进行垃圾回收（MinorGC），将伊甸园区中的不再被其他对象所引用的对象进行销毁。再加载新的对象放到伊甸园区。</li>
<li> 然后将伊甸园中的剩余对象移动到幸存者0区。</li>
<li> 如果再次触发垃圾回收，此时上次幸存下来的放到幸存者0区的，如果没有回收，就会放到幸存者1区。</li>
<li> 如果再次经历垃圾回收，此时会重新放回幸存者0区，接着再去幸存者1区。</li>
<li> 啥时候能去养老区呢？可以设置次数。默认是15次。可以设置新生区进入养老区的年龄限制，设置 JVM 参数：**-XX:MaxTenuringThreshold**=N 进行设置</li>
<li> 在养老区，相对悠闲。当养老区内存不足时，再次触发GC：Major GC，进行养老区的内存清理</li>
<li> 若养老区执行了Major GC之后，发现依然无法进行对象的保存，就会产生OOM异常。</li>
</ol>
<h3 id="图解对象分配（一般情况）"><a href="#图解对象分配（一般情况）" class="headerlink" title="图解对象分配（一般情况）"></a>图解对象分配（一般情况）</h3><p>1、我们创建的对象，一般都是存放在Eden区的，<strong>当我们Eden区满了后，就会触发GC操作</strong>，一般被称为 YGC / Minor GC操作</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0016.png">

<p>2、当我们进行一次垃圾收集后，红色的对象将会被回收，而绿色的独享还被占用着，存放在S0(Survivor From)区。同时我们给每个对象设置了一个年龄计数器，经过一次回收后还存在的对象，将其年龄加 1。</p>
<p>3、同时Eden区继续存放对象，当Eden区再次存满的时候，又会触发一个MinorGC操作，此时GC将会把 Eden和Survivor From中的对象进行一次垃圾收集，把存活的对象放到 Survivor To（S1）区，同时让存活的对象年龄 + 1</p>
<blockquote>
<p>下一次再进行GC的时候，</p>
<p>1、这一次的s0区为空，所以成为下一次GC的S1区</p>
<p>2、这一次的s1区则成为下一次GC的S0区</p>
<p>3、也就是说s0区和s1区在互相转换。</p>
</blockquote>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0017.png">

<p>4、我们继续不断的进行对象生成和垃圾回收，当Survivor中的对象的年龄达到15的时候，将会触发一次 Promotion 晋升的操作，也就是将年轻代中的对象晋升到老年代中</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0018.png">

<p>关于垃圾回收：频繁在新生区收集，很少在养老区收集，几乎不在永久区/元空间收集。</p>
<h3 id="特殊情况说明"><a href="#特殊情况说明" class="headerlink" title="特殊情况说明"></a>特殊情况说明</h3><p><strong>对象分配的特殊情况</strong></p>
<ol>
<li>如果来了一个新对象，先看看 Eden 是否放的下？<ul>
<li>  如果 Eden 放得下，则直接放到 Eden 区</li>
<li>  如果 Eden 放不下，则触发 YGC ，执行垃圾回收，看看还能不能放下？</li>
</ul>
</li>
<li>将对象放到老年区又有两种情况：<ul>
<li>  如果 Eden 执行了 YGC 还是无法放不下该对象，那没得办法，只能说明是超大对象，只能直接放到老年代</li>
<li>  那万一老年代都放不下，则先触发FullGC ，再看看能不能放下，放得下最好，但如果还是放不下，那只能报 OOM </li>
</ul>
</li>
<li> 如果 Eden 区满了，将对象往幸存区拷贝时，发现幸存区放不下啦，那只能便宜了某些新对象，让他们直接晋升至老年区</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0019.png">

<h3 id="常用调优工具"><a href="#常用调优工具" class="headerlink" title="常用调优工具"></a>常用调优工具</h3><ol>
<li> JDK命令行</li>
<li> Eclipse：Memory Analyzer Tool</li>
<li> Jconsole</li>
<li> Visual VM（实时监控，推荐）</li>
<li> Jprofiler（IDEA插件）</li>
<li> Java Flight Recorder（实时监控）</li>
<li> GCViewer</li>
<li> GCEasy</li>
</ol>
<h2 id="GC分类"><a href="#GC分类" class="headerlink" title="GC分类"></a>GC分类</h2><ol>
<li>我们都知道，JVM的调优的一个环节，也就是垃圾收集，我们需要尽量的避免垃圾回收，因为在垃圾回收的过程中，容易出现STW（Stop the World）的问题，<strong>而 Major GC 和 Full GC出现STW的时间，是Minor GC的10倍以上</strong></li>
<li>JVM在进行GC时，并非每次都对上面三个内存区域一起回收的，大部分时候回收的都是指新生代。针对Hotspot VM的实现，它里面的GC按照回收区域又分为两大种类型：一种是部分收集（Partial GC），一种是整堆收集（FullGC）</li>
</ol>
<ul>
<li><p>部分收集：不是完整收集整个Java堆的垃圾收集。其中又分为：</p>
<ul>
<li><strong>新生代收集</strong>（Minor GC/Young GC）：只是新生代（Eden，s0，s1）的垃圾收集</li>
<li><strong>老年代收集</strong>（Major GC/Old GC）：只是老年代的圾收集。</li>
<li>目前，只有CMS GC会有单独收集老年代的行为。</li>
<li>注意，很多时候Major GC会和Full GC混淆使用，需要具体分辨是老年代回收还是整堆回收。</li>
<li>混合收集（Mixed GC）：收集整个新生代以及部分老年代的垃圾收集。目前，只有G1 GC会有这种行为</li>
</ul>
</li>
<li><p><strong>整堆收集</strong>（Full GC）：收集整个java堆和方法区的垃圾收集。</p>
</li>
</ul>
<blockquote>
<p>由于历史原因，外界各种解读，majorGC和Full GC有些混淆。</p>
</blockquote>
<h3 id="Young-GC"><a href="#Young-GC" class="headerlink" title="Young GC"></a>Young GC</h3><p><strong>年轻代 GC（Minor GC）触发机制</strong></p>
<ol>
<li>当年轻代空间不足时，就会触发Minor GC，这里的年轻代满指的是Eden代满。Survivor满不会主动引发GC，在Eden区满的时候，会顺带触发s0区的GC，也就是被动触发GC（每次Minor GC会清理年轻代的内存）</li>
<li>因为Java对象大多都具备朝生夕灭的特性，所以Minor GC非常频繁，一般回收速度也比较快。这一定义既清晰又易于理解。</li>
<li>Minor GC会引发STW（Stop The World），暂停其它用户的线程，等垃圾回收结束，用户线程才恢复运行</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0020.png">



<h3 id="Major-Full-GC"><a href="#Major-Full-GC" class="headerlink" title="Major/Full GC"></a>Major/Full GC</h3><blockquote>
<p>Full GC有争议，后续详解两者区别，暂时先看着</p>
</blockquote>
<p><strong>老年代GC（MajorGC）触发机制</strong></p>
<ol>
<li><p> 指发生在老年代的GC，对象从老年代消失时，我们说 “Major Gc” 或 “Full GC” 发生了</p>
</li>
<li><p>出现了MajorGc，经常会伴随至少一次的Minor GC。（但非绝对的，在Parallel Scavenge收集器的收集策略里就有直接进行MajorGC的策略选择过程）</p>
<ul>
<li>  也就是在老年代空间不足时，会先尝试触发Minor GC（哈？我有点迷？），如果之后空间还不足，则触发Major GC</li>
</ul>
</li>
<li><p> Major GC的速度一般会比Minor GC慢10倍以上，STW的时间更长。</p>
</li>
<li><p> 如果Major GC后，内存还不足，就报OOM了</p>
</li>
</ol>
<p><strong>Full GC 触发机制（后面细讲）</strong></p>
<p><strong>触发Full GC执行的情况有如下五种：</strong></p>
<ol>
<li> 调用System.gc()时，系统建议执行FullGC，但是不必然执行</li>
<li> 老年代空间不足</li>
<li> 方法区空间不足</li>
<li> 通过Minor GC后进入老年代的平均大小大于老年代的可用内存</li>
<li> 由Eden区、survivor space0（From Space）区向survivor space1（To Space）区复制时，对象大小大于To Space可用内存，则把该对象转存到老年代，且老年代的可用内存小于该对象大小</li>
</ol>
<p>说明：Full GC 是开发或调优中尽量要避免的。这样STW时间会短一些</p>
<h3 id="GC日志分析"><a href="#GC日志分析" class="headerlink" title="GC日志分析"></a>GC日志分析</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 测试MinorGC 、 MajorGC、FullGC</span></span><br><span class="line"><span class="comment"> * -Xms9m -Xmx9m -XX:+PrintGCDetails</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> shkstart  shkstart@126.com</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@create</span> 2020  14:19</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GCTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            List&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            String a = <span class="string">&quot;atguigu.com&quot;</span>;</span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                list.add(a);</span><br><span class="line">                a = a + a;</span><br><span class="line">                i++;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            t.printStackTrace();</span><br><span class="line">            System.out.println(<span class="string">&quot;遍历次数为：&quot;</span> + i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[GC (Allocation Failure) [PSYoungGen: 2037K-&gt;504K(2560K)] 2037K-&gt;728K(9728K), <span class="number">0.0455865</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.06</span> secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 2246K-&gt;496K(2560K)] 2470K-&gt;1506K(9728K), <span class="number">0.0009094</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.00</span> secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 2294K-&gt;488K(2560K)] 3305K-&gt;2210K(9728K), <span class="number">0.0009568</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.00</span> secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 1231K-&gt;488K(2560K)] 7177K-&gt;6434K(9728K), <span class="number">0.0005594</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.00</span> secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 488K-&gt;472K(2560K)] 6434K-&gt;6418K(9728K), <span class="number">0.0005890</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.00</span> secs] </span><br><span class="line">[<span class="function">Full <span class="title">GC</span> <span class="params">(Allocation Failure)</span> [PSYoungGen: 472K-&gt;0<span class="title">K</span><span class="params">(2560K)</span>] [ParOldGen: 5946K-&gt;4944<span class="title">K</span><span class="params">(7168K)</span>] 6418K-&gt;4944<span class="title">K</span><span class="params">(9728K)</span>, [Metaspace: 3492K-&gt;3492<span class="title">K</span><span class="params">(1056768K)</span>], 0.0045270 secs] [Times: user</span>=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 0K-&gt;0K(1536K)] 4944K-&gt;4944K(8704K), <span class="number">0.0004954</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.00</span> secs] </span><br><span class="line">[<span class="function">Full <span class="title">GC</span> <span class="params">(Allocation Failure)</span> java.lang.OutOfMemoryError: Java heap space</span></span><br><span class="line"><span class="function">	at java.util.Arrays.<span class="title">copyOf</span><span class="params">(Arrays.java:<span class="number">3332</span>)</span></span></span><br><span class="line"><span class="function">	at java.lang.AbstractStringBuilder.<span class="title">ensureCapacityInternal</span><span class="params">(AbstractStringBuilder.java:<span class="number">124</span>)</span></span></span><br><span class="line"><span class="function">	at java.lang.AbstractStringBuilder.<span class="title">append</span><span class="params">(AbstractStringBuilder.java:<span class="number">448</span>)</span></span></span><br><span class="line"><span class="function">	at java.lang.StringBuilder.<span class="title">append</span><span class="params">(StringBuilder.java:<span class="number">136</span>)</span></span></span><br><span class="line"><span class="function">	at com.atguigu.java1.GCTest.<span class="title">main</span><span class="params">(GCTest.java:<span class="number">20</span>)</span></span></span><br><span class="line"><span class="function">[PSYoungGen: 0K-&gt;0<span class="title">K</span><span class="params">(1536K)</span>] [ParOldGen: 4944K-&gt;4877<span class="title">K</span><span class="params">(7168K)</span>] 4944K-&gt;4877<span class="title">K</span><span class="params">(8704K)</span>, [Metaspace: 3492K-&gt;3492<span class="title">K</span><span class="params">(1056768K)</span>], 0.0076061 secs] [Times: user</span>=<span class="number">0.00</span> sys=<span class="number">0.02</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">遍历次数为：<span class="number">16</span></span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen      total 1536K, used 60K [<span class="number">0x00000000ffd00000</span>, <span class="number">0x0000000100000000</span>, <span class="number">0x0000000100000000</span>)</span><br><span class="line">  eden space 1024K, <span class="number">5</span>% used [<span class="number">0x00000000ffd00000</span>,<span class="number">0x00000000ffd0f058</span>,<span class="number">0x00000000ffe00000</span>)</span><br><span class="line">  from space 512K, <span class="number">0</span>% used [<span class="number">0x00000000fff80000</span>,<span class="number">0x00000000fff80000</span>,<span class="number">0x0000000100000000</span>)</span><br><span class="line">  to   space 1024K, <span class="number">0</span>% used [<span class="number">0x00000000ffe00000</span>,<span class="number">0x00000000ffe00000</span>,<span class="number">0x00000000fff00000</span>)</span><br><span class="line"> ParOldGen       total 7168K, used 4877K [<span class="number">0x00000000ff600000</span>, <span class="number">0x00000000ffd00000</span>, <span class="number">0x00000000ffd00000</span>)</span><br><span class="line">  object space 7168K, <span class="number">68</span>% used [<span class="number">0x00000000ff600000</span>,<span class="number">0x00000000ffac3408</span>,<span class="number">0x00000000ffd00000</span>)</span><br><span class="line"> Metaspace       used 3525K, capacity 4502K, committed 4864K, reserved 1056768K</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">space</span>    <span class="title">used</span> 391<span class="title">K</span>, <span class="title">capacity</span> 394<span class="title">K</span>, <span class="title">committed</span> 512<span class="title">K</span>, <span class="title">reserved</span> 1048576<span class="title">K</span></span></span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[GC (Allocation Failure) [PSYoungGen: 2037K-&gt;504K(2560K)] 2037K-&gt;728K(9728K), <span class="number">0.0455865</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.06</span> secs] </span><br><span class="line"></span><br></pre></td></tr></table></figure>



<ul>
<li><p>[PSYoungGen: 2037K-&gt;504K(2560K)]：年轻代总空间为 2560K ，当前占用 2037K ，经过垃圾回收后剩余504K</p>
</li>
<li><p>2037K-&gt;728K(9728K)：堆内存总空间为 9728K ，当前占用2037K ，经过垃圾回收后剩余728K</p>
</li>
</ul>
<h2 id="堆空间分代思想"><a href="#堆空间分代思想" class="headerlink" title="堆空间分代思想"></a>堆空间分代思想</h2><p>为什么要把Java堆分代？不分代就不能正常工作了吗？经研究，不同对象的生命周期不同。70%-99%的对象是临时对象。</p>
<ul>
<li>  新生代：有Eden、两块大小相同的survivor（又称为from/to或s0/s1）构成，to总为空。</li>
<li>  老年代：存放新生代中经历多次GC仍然存活的对象。</li>
</ul>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0021.png">



<p>其实不分代完全可以，分代的唯一理由就是优化GC性能。</p>
<ul>
<li>如果没有分代，那所有的对象都在一块，就如同把一个学校的人都关在一个教室。GC的时候要找到哪些对象没用，这样就会对堆的所有区域进行扫描。（性能低）</li>
</ul>
<ul>
<li>  而很多对象都是朝生夕死的，如果分代的话，把新创建的对象放到某一地方，当GC的时候先把这块存储“朝生夕死”对象的区域进行回收，这样就会腾出很大的空间出来。（多回收新生代，少回收老年代，性能会提高很多）</li>
</ul>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0022.png">



<h2 id="对象内存分配策略"><a href="#对象内存分配策略" class="headerlink" title="对象内存分配策略"></a>对象内存分配策略</h2><ol>
<li> 如果对象在Eden出生并经过第一次Minor GC后仍然存活，并且能被Survivor容纳的话，将被移动到Survivor空间中，并将对象年龄设为1。</li>
<li> 对象在Survivor区中每熬过一次MinorGC，年龄就增加1岁，当它的年龄增加到一定程度（默认为15岁，其实每个JVM、每个GC都有所不同）时，就会被晋升到老年代</li>
<li> 对象晋升老年代的年龄阀值，可以通过选项**-XX:MaxTenuringThreshold**来设置</li>
</ol>
<p><strong>针对不同年龄段的对象分配原则如下所示：</strong></p>
<ol>
<li> <strong>优先分配到Eden</strong>：开发中比较长的字符串或者数组，会直接存在老年代，但是因为新创建的对象都是朝生夕死的，所以这个大对象可能也很快被回收，但是因为老年代触发Major GC的次数比 Minor GC要更少，因此可能回收起来就会比较慢</li>
<li> <strong>大对象直接分配到老年代</strong>：尽量避免程序中出现过多的大对象</li>
<li> <strong>长期存活的对象分配到老年代</strong></li>
<li> <strong>动态对象年龄判断</strong>：如果Survivor区中相同年龄的所有对象大小的总和大于Survivor空间的一半，年龄大于或等于该年龄的对象可以直接进入老年代，无须等到MaxTenuringThreshold中要求的年龄。</li>
<li> <strong>空间分配担保</strong>： -XX:HandlePromotionFailure 。</li>
</ol>
<blockquote>
<p>一些细节放在后面说</p>
</blockquote>
<h2 id="TLAB为对象分配内存（保证线程安全）"><a href="#TLAB为对象分配内存（保证线程安全）" class="headerlink" title="TLAB为对象分配内存（保证线程安全）"></a>TLAB为对象分配内存（保证线程安全）</h2><h3 id="为什么有-TLAB"><a href="#为什么有-TLAB" class="headerlink" title="为什么有 TLAB"></a>为什么有 TLAB</h3><ol start="2">
<li> 堆区是线程共享区域，任何线程都可以访问到堆区中的共享数据</li>
<li> 由于对象实例的创建在JVM中非常频繁，因此在并发环境下从堆区中划分内存空间是线程不安全的</li>
<li> 为避免多个线程操作同一地址，需要使用<strong>加锁等机制</strong>，进而影响分配速度。</li>
</ol>
<h3 id="什么是-TLAB"><a href="#什么是-TLAB" class="headerlink" title="什么是 TLAB"></a>什么是 TLAB</h3><p>TLAB（Thread Local Allocation Buffer）</p>
<ol>
<li> 从内存模型而不是垃圾收集的角度，对Eden区域继续进行划分，<strong>JVM为每个线程分配了一个私有缓存区域，它包含在Eden空间内</strong>。</li>
<li> 多线程同时分配内存时，使用TLAB可以避免一系列的非线程安全问题，同时还能够提升内存分配的吞吐量，因此我们可以将这种内存分配方式称之为<strong>快速分配策略</strong>。</li>
<li> 据我所知所有OpenJDK衍生出来的JVM都提供了TLAB的设计。</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0023.png">

<p>1、每个线程都有一个TLAB空间</p>
<p>2、当一个线程的TLAB存满时，可以使用公共区域（蓝色）的</p>
<h3 id="TLAB再说明"><a href="#TLAB再说明" class="headerlink" title="TLAB再说明"></a>TLAB再说明</h3><ol>
<li><p>尽管不是所有的对象实例都能够在TLAB中成功分配内存，但<strong>JVM确实是将TLAB作为内存分配的首选</strong>。</p>
</li>
<li><p>在程序中，开发人员可以通过选项“**-XX:UseTLAB**”设置是否开启TLAB空间。</p>
</li>
<li><p>默认情况下，TLAB空间的内存非常小，仅占有整个Eden空间的1%，当然我们可以通过选项“**-XX:TLABWasteTargetPercent**”设置TLAB空间所占用Eden空间的百分比大小。</p>
</li>
<li><p>一旦对象在TLAB空间分配内存失败时，JVM就会尝试着通过<strong>使用加锁机制确保数据操作的原子性</strong>，从而直接在Eden空间中分配内存。</p>
</li>
</ol>
<blockquote>
<p>1、哪个线程要分配内存，就在哪个线程的本地缓冲区中分配，只有本地缓冲区用完 了，<strong>分配新的缓存区时才需要同步锁定</strong>                   —-这是《深入理解JVM》–第三版里说的</p>
<p>2、和这里讲的有点不同。我猜测说的意思是某一次分配，如果TLAB用完了，那么<strong>这一次</strong>先在Eden区直接分配。空闲下来后再加锁分配新的TLAB（TLAB内存较大，分配时间应该较长）</p>
</blockquote>
<p><strong>TLAB 分配过程</strong></p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_005/0024.png">



<h2 id="堆空间参数设置"><a href="#堆空间参数设置" class="headerlink" title="堆空间参数设置"></a>堆空间参数设置</h2><h3 id="常用参数设置"><a href="#常用参数设置" class="headerlink" title="常用参数设置"></a>常用参数设置</h3><blockquote>
<p><strong>官方文档</strong>：<a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html</a></p>
<p>我们只说常用的</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 测试堆空间常用的jvm参数：</span></span><br><span class="line"><span class="comment"> * -XX:+PrintFlagsInitial : 查看所有的参数的默认初始值</span></span><br><span class="line"><span class="comment"> * -XX:+PrintFlagsFinal  ：查看所有的参数的最终值（可能会存在修改，不再是初始值）</span></span><br><span class="line"><span class="comment"> *      具体查看某个参数的指令： jps：查看当前运行中的进程</span></span><br><span class="line"><span class="comment"> *                             jinfo -flag SurvivorRatio 进程id</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * -Xms：初始堆空间内存 （默认为物理内存的1/64）</span></span><br><span class="line"><span class="comment"> * -Xmx：最大堆空间内存（默认为物理内存的1/4）</span></span><br><span class="line"><span class="comment"> * -Xmn：设置新生代的大小。(初始值及最大值)</span></span><br><span class="line"><span class="comment"> * -XX:NewRatio：配置新生代与老年代在堆结构的占比</span></span><br><span class="line"><span class="comment"> * -XX:SurvivorRatio：设置新生代中Eden和S0/S1空间的比例</span></span><br><span class="line"><span class="comment"> * -XX:MaxTenuringThreshold：设置新生代垃圾的最大年龄</span></span><br><span class="line"><span class="comment"> * -XX:+PrintGCDetails：输出详细的GC处理日志</span></span><br><span class="line"><span class="comment"> * 打印gc简要信息：① -XX:+PrintGC   ② -verbose:gc</span></span><br><span class="line"><span class="comment"> * -XX:HandlePromotionFailure：是否设置空间分配担保</span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure>



<h3 id="空间分配担保"><a href="#空间分配担保" class="headerlink" title="空间分配担保"></a>空间分配担保</h3><p>1、在发生Minor GC之前，虚拟机会检查老年代最大可用的连续空间是否大于新生代所有对象的总空间。</p>
<ul>
<li>  如果大于，则此次Minor GC是安全的</li>
<li>如果小于，则虚拟机会查看**-XX:HandlePromotionFailure**设置值是否允担保失败。<ul>
<li>如果HandlePromotionFailure=true，那么会继续检查<strong>老年代最大可用连续空间是否大于历次晋升到老年代的对象的平均大小</strong>。<ul>
<li>  如果大于，则尝试进行一次Minor GC，但这次Minor GC依然是有风险的；</li>
<li>  如果小于，则进行一次Full GC。</li>
</ul>
</li>
<li>如果HandlePromotionFailure=false，则进行一次Full GC。</li>
</ul>
</li>
</ul>
<p><strong>历史版本</strong></p>
<ol>
<li> 在JDK6 Update 24之后，HandlePromotionFailure参数不会再影响到虚拟机的空间分配担保策略，观察openJDK中的源码变化，虽然源码中还定义了HandlePromotionFailure参数，但是在代码中已经不会再使用它。</li>
<li> JDK6 Update 24之后的规则变为<strong>只要老年代的连续空间大于新生代对象总大小或者历次晋升的平均大小就会进行Minor GC</strong>，否则将进行Full GC。即 HandlePromotionFailure=true</li>
</ol>
<h2 id="堆是分配对象的唯一选择么？"><a href="#堆是分配对象的唯一选择么？" class="headerlink" title="堆是分配对象的唯一选择么？"></a>堆是分配对象的唯一选择么？</h2><p><strong>在《深入理解Java虚拟机》中关于Java堆内存有这样一段描述：</strong></p>
<ol>
<li>随着JIT编译期的发展与<strong>逃逸分析技术</strong>逐渐成熟，<strong>栈上分配、标量替换</strong>优化技术将会导致一些微妙的变化，所有的对象都分配到堆上也渐渐变得不那么“绝对”了。</li>
<li>在Java虚拟机中，对象是在Java堆中分配内存的，这是一个普遍的常识。但是，有一种特殊情况，那就是<strong>如果经过逃逸分析（Escape Analysis）后发现，一个对象并没有逃逸出方法的话，那么就可能被优化成栈上分配</strong>。这样就无需在堆上分配内存，也无须进行垃圾回收了。这也是最常见的堆外存储技术。</li>
<li>此外，前面提到的基于OpenJDK深度定制的TaoBao VM，其中创新的GCIH（GC invisible heap）技术实现off-heap，将生命周期较长的Java对象从heap中移至heap外，并且GC不能管理GCIH内部的Java对象，以此达到降低GC的回收频率和提升GC的回收效率的目的。</li>
</ol>
<h3 id="逃逸分析"><a href="#逃逸分析" class="headerlink" title="逃逸分析"></a>逃逸分析</h3><ol>
<li> 如何将堆上的对象分配到栈，需要使用逃逸分析手段。</li>
<li> 这是一种可以有效减少Java程序中同步负载和内存堆分配压力的跨函数全局数据流分析算法。</li>
<li> 通过逃逸分析，Java Hotspot编译器能够分析出一个新的对象的引用的使用范围从而决定是否要将这个对象分配到堆上。</li>
<li>逃逸分析的基本行为就是分析对象动态作用域：<ul>
<li>  当一个对象在方法中被定义后，对象只在方法内部使用，则认为没有发生逃逸。</li>
<li>  当一个对象在方法中被定义后，它被外部方法所引用，则认为发生逃逸。例如作为调用参数传递到其他地方中。</li>
</ul>
</li>
</ol>
<p><strong>逃逸分析举例</strong></p>
<p>1、没有发生逃逸的对象，则可以分配到栈（无线程安全问题）上，随着方法执行的结束，栈空间就被移除（也就无需GC）</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">my_method</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    V v = <span class="keyword">new</span> V();</span><br><span class="line">    <span class="comment">// use v</span></span><br><span class="line">    <span class="comment">// ....</span></span><br><span class="line">    v = <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>2、下面代码中的 StringBuffer sb 发生了逃逸，不能在栈上分配</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> StringBuffer <span class="title">createStringBuffer</span><span class="params">(String s1, String s2)</span> </span>&#123;</span><br><span class="line">    StringBuffer sb = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">    sb.append(s1);</span><br><span class="line">    sb.append(s2);</span><br><span class="line">    <span class="keyword">return</span> sb;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>3、如果想要StringBuffer sb不发生逃逸，可以这样写</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">createStringBuffer</span><span class="params">(String s1, String s2)</span> </span>&#123;</span><br><span class="line">    StringBuffer sb = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">    sb.append(s1);</span><br><span class="line">    sb.append(s2);</span><br><span class="line">    <span class="keyword">return</span> sb.toString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 逃逸分析</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *  如何快速的判断是否发生了逃逸分析，大家就看new的对象实体是否有可能在方法外被调用。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EscapeAnalysis</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> EscapeAnalysis obj;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    方法返回EscapeAnalysis对象，发生逃逸</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> EscapeAnalysis <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> obj == <span class="keyword">null</span>? <span class="keyword">new</span> EscapeAnalysis() : obj;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    为成员属性赋值，发生逃逸</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setObj</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.obj = <span class="keyword">new</span> EscapeAnalysis();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//思考：如果当前的obj引用声明为static的？仍然会发生逃逸。</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    对象的作用域仅在当前方法中有效，没有发生逃逸</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useEscapeAnalysis</span><span class="params">()</span></span>&#123;</span><br><span class="line">        EscapeAnalysis e = <span class="keyword">new</span> EscapeAnalysis();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    引用成员变量的值，发生逃逸</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useEscapeAnalysis1</span><span class="params">()</span></span>&#123;</span><br><span class="line">        EscapeAnalysis e = getInstance();</span><br><span class="line">        <span class="comment">//getInstance().xxx()同样会发生逃逸</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p><strong>逃逸分析参数设置</strong></p>
<ol>
<li>在JDK 1.7 版本之后，HotSpot中默认就已经开启了逃逸分析</li>
<li>如果使用的是较早的版本，开发人员则可以通过：<ul>
<li>  选项“-XX:+DoEscapeAnalysis”显式开启逃逸分析</li>
<li>  通过选项“-XX:+PrintEscapeAnalysis”查看逃逸分析的筛选结果</li>
</ul>
</li>
</ol>
<p><strong>总结</strong></p>
<p>开发中能使用局部变量的，就不要使用在方法外定义。</p>
<h3 id="代码优化"><a href="#代码优化" class="headerlink" title="代码优化"></a>代码优化</h3><p>使用逃逸分析，编译器可以对代码做如下优化：</p>
<ol>
<li> <strong>栈上分配</strong>：将堆分配转化为栈分配。如果一个对象在子程序中被分配，要使指向该对象的指针永远不会发生逃逸，对象可能是栈上分配的候选，而不是堆上分配</li>
<li> <strong>同步省略</strong>：如果一个对象被发现只有一个线程被访问到，那么对于这个对象的操作可以不考虑同步。</li>
<li> <strong>分离对象或标量替换</strong>：有的对象可能不需要作为一个连续的内存结构存在也可以被访问到，那么对象的部分（或全部）可以不存储在内存，而是存储在CPU寄存器中。</li>
</ol>
<h3 id="栈上分配"><a href="#栈上分配" class="headerlink" title="栈上分配"></a>栈上分配</h3><ol>
<li> JIT编译器在编译期间根据逃逸分析的结果，发现如果一个对象并没有逃逸出方法的话，就可能被优化成栈上分配。分配完成后，继续在调用栈内执行，最后线程结束，栈空间被回收，局部变量对象也被回收。这样就无须进行垃圾回收了。</li>
<li> 常见的栈上分配的场景：在逃逸分析中，已经说明了，分别是给成员变量赋值、方法返回值、实例引用传递。</li>
</ol>
<p><strong>栈上分配举例</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 栈上分配测试</span></span><br><span class="line"><span class="comment"> * -Xmx128m -Xms128m -XX:-DoEscapeAnalysis -XX:+PrintGCDetails</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StackAllocation</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10000000</span>; i++) &#123;</span><br><span class="line">            alloc();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 查看执行时间</span></span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;花费的时间为： &quot;</span> + (end - start) + <span class="string">&quot; ms&quot;</span>);</span><br><span class="line">        <span class="comment">// 为了方便查看堆内存中对象个数，线程sleep</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e1) &#123;</span><br><span class="line">            e1.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">alloc</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = <span class="keyword">new</span> User();<span class="comment">//未发生逃逸</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">[GC (Allocation Failure) [PSYoungGen: 33280K-&gt;808K(38400K)] 33280K-&gt;816K(125952K), 0.0483350 secs] [Times: user&#x3D;0.00 sys&#x3D;0.00, real&#x3D;0.06 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 34088K-&gt;808K(38400K)] 34096K-&gt;816K(125952K), 0.0008411 secs] [Times: user&#x3D;0.00 sys&#x3D;0.00, real&#x3D;0.00 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 34088K-&gt;792K(38400K)] 34096K-&gt;800K(125952K), 0.0008427 secs] [Times: user&#x3D;0.00 sys&#x3D;0.00, real&#x3D;0.00 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 34072K-&gt;808K(38400K)] 34080K-&gt;816K(125952K), 0.0012223 secs] [Times: user&#x3D;0.08 sys&#x3D;0.00, real&#x3D;0.00 secs] </span><br><span class="line">花费的时间为： 114 ms</span><br></pre></td></tr></table></figure>





<p>1、JVM 参数设置</p>
<p>-Xmx128m -Xms128m -XX:-DoEscapeAnalysis -XX:+PrintGCDetails</p>
<p>2、日志打印：发生了 GC ，耗时 114ms</p>
<p><strong>开启逃逸分析的情况</strong></p>
<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">花费的时间为： 5 ms</span><br></pre></td></tr></table></figure>

<p>1、参数设置</p>
<p>-Xmx128m -Xms128m -XX:+DoEscapeAnalysis -XX:+PrintGCDetails</p>
<p>2、日志打印：并没有发生 GC ，耗时5ms 。</p>
<h3 id="同步省略（同步消除）"><a href="#同步省略（同步消除）" class="headerlink" title="同步省略（同步消除）"></a>同步省略（同步消除）</h3><ol>
<li>线程同步的代价是相当高的，同步的后果是降低并发性和性能。</li>
<li>在动态编译同步块的时候，JIT编译器可以借助逃逸分析来<strong>判断同步块所使用的锁对象是否只能够被一个线程访问而没有被发布到其他线程</strong>。</li>
<li>如果没有，那么JIT编译器在编译这个同步块的时候就会取消对这部分代码的同步。这样就能大大提高并发性和性能。这个<strong>取消同步的过程就叫同步省略，也叫锁消除</strong>。</li>
</ol>
<p>例如下面的代码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Object hollis = <span class="keyword">new</span> Object();</span><br><span class="line">    <span class="keyword">synchronized</span>(hollis) &#123;</span><br><span class="line">        System.out.println(hollis);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>代码中对hollis这个对象加锁，但是hollis对象的生命周期只在f()方法中，并不会被其他线程所访问到，所以在JIT编译阶段就会被优化掉，优化成：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Object hellis = <span class="keyword">new</span> Object();</span><br><span class="line">	System.out.println(hellis);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<p><strong>字节码分析</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">public class SynchronizedTest &#123;</span><br><span class="line">    public void f() &#123;</span><br><span class="line">        Object hollis &#x3D; new Object();</span><br><span class="line">        synchronized(hollis) &#123;</span><br><span class="line">            System.out.println(hollis);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> 0 new #2 &lt;java/lang/Object&gt;</span><br><span class="line"> <span class="number">3</span> dup</span><br><span class="line"> 4 invokespecial #1 &lt;java/lang/Object.&lt;init&gt;&gt;</span><br><span class="line"> <span class="number">7</span> astore_1</span><br><span class="line"> <span class="number">8</span> aload_1</span><br><span class="line"> <span class="number">9</span> dup</span><br><span class="line"><span class="number">10</span> astore_2</span><br><span class="line"><span class="number">11</span> monitorenter</span><br><span class="line">12 getstatic #3 &lt;java/lang/System.out&gt;</span><br><span class="line"><span class="number">15</span> aload_1</span><br><span class="line">16 invokevirtual #4 &lt;java/io/PrintStream.println&gt;</span><br><span class="line"><span class="number">19</span> aload_2</span><br><span class="line"><span class="number">20</span> monitorexit</span><br><span class="line"><span class="number">21</span> goto <span class="number">29</span> (+<span class="number">8</span>)</span><br><span class="line"><span class="number">24</span> astore_3</span><br><span class="line"><span class="number">25</span> aload_2</span><br><span class="line"><span class="number">26</span> monitorexit</span><br><span class="line"><span class="number">27</span> aload_3</span><br><span class="line"><span class="number">28</span> athrow</span><br><span class="line"><span class="number">29</span> <span class="keyword">return</span></span><br></pre></td></tr></table></figure>

<p>注意：字节码文件中并没有进行优化，可以看到加锁和释放锁的操作依然存在，<strong>同步省略操作是在解释运行时发生的</strong></p>
<h3 id="标量替换"><a href="#标量替换" class="headerlink" title="标量替换"></a>标量替换</h3><p><strong>分离对象或标量替换</strong></p>
<ol>
<li>标量（scalar）是指一个无法再分解成更小的数据的数据。Java中的原始数据类型就是标量。</li>
<li>相对的，那些还可以分解的数据叫做聚合量（Aggregate），Java中的对象就是聚合量，因为他可以分解成其他聚合量和标量。</li>
<li>在JIT阶段，如果经过逃逸分析，发现一个对象不会被外界访问的话，那么经过JIT优化，就会把这个对象拆解成若干个其中包含的若干个成员变量来代替。这个过程就是标量替换。</li>
</ol>
<p><strong>标量替换举例</strong></p>
<p>代码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">    alloc();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">alloc</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Point point = <span class="keyword">new</span> Point(<span class="number">1</span>,<span class="number">2</span>);</span><br><span class="line">    System.out.println(<span class="string">&quot;point.x&quot;</span> + point.x + <span class="string">&quot;;point.y&quot;</span> + point.y);</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Point</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> x;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> y;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>以上代码，经过标量替换后，就会变成</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">alloc</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> x = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> y = <span class="number">2</span>;</span><br><span class="line">    System.out.println(<span class="string">&quot;point.x = &quot;</span> + x + <span class="string">&quot;; point.y=&quot;</span> + y);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ol>
<li> 可以看到，Point这个聚合量经过逃逸分析后，发现他并没有逃逸，就被替换成两个聚合量了。</li>
<li> 那么标量替换有什么好处呢？就是可以大大减少堆内存的占用。因为一旦不需要创建对象了，那么就不再需要分配堆内存了。</li>
<li> 标量替换为栈上分配提供了很好的基础。</li>
</ol>
<p><strong>标量替换参数设置</strong></p>
<p>参数 -XX:+ElimilnateAllocations：开启了标量替换（默认打开），允许将对象打散分配在栈上。</p>
<p><strong>代码示例</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 标量替换测试</span></span><br><span class="line"><span class="comment"> *  -Xmx100m -Xms100m -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:-EliminateAllocations</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> shkstart  shkstart@126.com</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@create</span> 2020  12:01</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ScalarReplace</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">int</span> id;</span><br><span class="line">        <span class="keyword">public</span> String name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">alloc</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User u = <span class="keyword">new</span> User();<span class="comment">//未发生逃逸</span></span><br><span class="line">        u.id = <span class="number">5</span>;</span><br><span class="line">        u.name = <span class="string">&quot;www.atguigu.com&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10000000</span>; i++) &#123;</span><br><span class="line">            alloc();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;花费的时间为： &quot;</span> + (end - start) + <span class="string">&quot; ms&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>未开启标量替换</strong></p>
<p>1、JVM 参数</p>
<p>-Xmx100m -Xms100m -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:-EliminateAllocations</p>
<p>2、日志</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[GC (Allocation Failure)  25600K-&gt;880K(98304K), <span class="number">0.0012658</span> secs]</span><br><span class="line">[GC (Allocation Failure)  26480K-&gt;832K(98304K), <span class="number">0.0012124</span> secs]</span><br><span class="line">[GC (Allocation Failure)  26432K-&gt;784K(98304K), <span class="number">0.0009719</span> secs]</span><br><span class="line">[GC (Allocation Failure)  26384K-&gt;832K(98304K), <span class="number">0.0009071</span> secs]</span><br><span class="line">[GC (Allocation Failure)  26432K-&gt;768K(98304K), <span class="number">0.0010643</span> secs]</span><br><span class="line">[GC (Allocation Failure)  26368K-&gt;824K(101376K), <span class="number">0.0012354</span> secs]</span><br><span class="line">[GC (Allocation Failure)  32568K-&gt;712K(100864K), <span class="number">0.0011291</span> secs]</span><br><span class="line">[GC (Allocation Failure)  32456K-&gt;712K(100864K), <span class="number">0.0006368</span> secs]</span><br><span class="line">花费的时间为： <span class="number">99</span> ms</span><br></pre></td></tr></table></figure>



<p><strong>开启标量替换</strong></p>
<p>1、JVM 参数</p>
<p>-Xmx100m -Xms100m -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:+EliminateAllocations</p>
<p>2、日志：时间减少很多，且无GC</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">花费的时间为： 6 ms</span><br></pre></td></tr></table></figure>





<p>上述代码在主函数中调用了1亿次alloc()方法，进行对象创建由于User对象实例需要占据约16字节的空间，因此累计分配空间达到将近1.5GB。如果堆空间小于这个值，就必然会发生GC。使用如下参数运行上述代码：</p>
<p><code>-server -Xmx100m -Xms100m -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:+EliminateAllocations</code></p>
<p>这里设置参数如下：</p>
<ol>
<li> 参数 -server：启动Server模式，因为在server模式下，才可以启用逃逸分析。</li>
<li> 参数 -XX:+DoEscapeAnalysis：启用逃逸分析</li>
<li> 参数 -Xmx10m：指定了堆空间最大为10MB</li>
<li> 参数 -XX:+PrintGC：将打印GC日志。</li>
<li> 参数 -XX:+EliminateAllocations：开启了标量替换（默认打开），允许将对象打散分配在栈上，比如对象拥有id和name两个字段，那么这两个字段将会被视为两个独立的局部变量进行分配</li>
</ol>
<h3 id="逃逸分析的不足"><a href="#逃逸分析的不足" class="headerlink" title="逃逸分析的不足"></a>逃逸分析的不足</h3><ol>
<li> 关于逃逸分析的论文在1999年就已经发表了，但直到JDK1.6才有实现，而且这项技术到如今也并不是十分成熟的。</li>
<li> 其根本原因就是无法保证逃逸分析的性能消耗一定能高于他的消耗。虽然经过逃逸分析可以做标量替换、栈上分配、和锁消除。但是逃逸分析自身也是需要进行一系列复杂的分析的，这其实也是一个相对耗时的过程。</li>
<li> 一个极端的例子，就是经过逃逸分析之后，发现没有一个对象是不逃逸的。那这个逃逸分析的过程就白白浪费掉了。</li>
<li> 虽然这项技术并不十分成熟，但是它也是即时编译器优化技术中一个十分重要的手段。</li>
<li> 注意到有一些观点，认为通过逃逸分析，JVM会在栈上分配那些不会逃逸的对象，这在理论上是可行的，但是取决于JVM设计者的选择。据我所知，<strong>Oracle Hotspot JVM中并未这么做</strong>（刚刚演示的效果，是因为HotSpot实现了标量替换），这一点在逃逸分析相关的文档里已经说明，<strong>所以可以明确在HotSpot虚拟机上，所有的对象实例都是创建在堆上</strong>。</li>
<li> 目前很多书籍还是基于JDK7以前的版本，JDK已经发生了很大变化，intern字符串的缓存和静态变量曾经都被分配在永久代上，而永久代已经被元数据区取代。但是<strong>intern字符串缓存和静态变量并不是被转移到元数据区，而是直接在堆上分配</strong>，<strong>所以这一点同样符合前面一点的结论：对象实例都是分配在堆上</strong>。</li>
</ol>
<blockquote>
<p><strong>堆是分配对象的唯一选择么？</strong></p>
</blockquote>
<p>综上：<strong>对象实例都是分配在堆上</strong>。What the fuck？</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><ol>
<li>年轻代是对象的诞生、成长、消亡的区域，一个对象在这里产生、应用，最后被垃圾回收器收集、结束生命。</li>
<li>老年代放置长生命周期的对象，通常都是从Survivor区域筛选拷贝过来的Java对象。</li>
<li>当然，也有特殊情况，我们知道普通的对象可能会被分配在TLAB上；</li>
<li>如果对象较大，无法分配在 TLAB 上，则JVM会试图直接分配在Eden其他位置上；</li>
<li>如果对象太大，完全无法在新生代找到足够长的连续空闲空间，JVM就会直接分配到老年代。</li>
<li>当GC只发生在年轻代中，回收年轻代对象的行为被称为Minor GC。</li>
<li>当GC发生在老年代时则被称为Major GC或者Full GC。</li>
<li> 一般的，Minor GC的发生频率要比Major GC高很多，即老年代中垃圾回收发生的频率将大大低于年轻代。</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/50ac3a1c.html">https://imlql.cn/post/50ac3a1c.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JVM/">JVM</a><a class="post-meta__tags" href="/tags/%E8%99%9A%E6%8B%9F%E6%9C%BA/">虚拟机</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/136cd965.html"><img class="prev-cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JVM系列-第6章-方法区</div></div></a></div><div class="next-post pull-right"><a href="/post/5b1b6560.html"><img class="next-cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JVM系列-第4章-虚拟机栈</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/debff71a.html" title="JVM系列-第7章-对象的实例化内存布局与访问定位"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-14</div><div class="title">JVM系列-第7章-对象的实例化内存布局与访问定位</div></div></a></div><div><a href="/post/8c954c6.html" title="JVM系列-第1章-JVM与Java体系结构"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-02</div><div class="title">JVM系列-第1章-JVM与Java体系结构</div></div></a></div><div><a href="/post/2e0079af.html" title="JVM系列-第2章-类加载子系统"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-02</div><div class="title">JVM系列-第2章-类加载子系统</div></div></a></div><div><a href="/post/a7ad3cab.html" title="JVM系列-第3章-运行时数据区"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-09</div><div class="title">JVM系列-第3章-运行时数据区</div></div></a></div><div><a href="/post/408712f4.html" title="JVM系列-第8章-执行引擎"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-15</div><div class="title">JVM系列-第8章-执行引擎</div></div></a></div><div><a href="/post/d54daa0f.html" title="JVM系列-第10章-垃圾回收概述和相关算法"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-16</div><div class="title">JVM系列-第10章-垃圾回收概述和相关算法</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A0%86"><span class="toc-text">堆</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A0%86%E7%9A%84%E6%A0%B8%E5%BF%83%E6%A6%82%E8%BF%B0"><span class="toc-text">堆的核心概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A0%86%E4%B8%8E%E8%BF%9B%E7%A8%8B"><span class="toc-text">堆与进程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A0%86%E5%86%85%E5%AD%98%E7%BB%86%E5%88%86"><span class="toc-text">堆内存细分</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JVisualVM%E5%8F%AF%E8%A7%86%E5%8C%96%E6%9F%A5%E7%9C%8B%E5%A0%86%E5%86%85%E5%AD%98"><span class="toc-text">JVisualVM可视化查看堆内存</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E5%A0%86%E5%86%85%E5%AD%98%E5%A4%A7%E5%B0%8F%E4%B8%8E-OOM"><span class="toc-text">设置堆内存大小与 OOM</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E5%A0%86%E5%86%85%E5%AD%98"><span class="toc-text">设置堆内存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#OOM"><span class="toc-text">OOM</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B9%B4%E8%BD%BB%E4%BB%A3%E4%B8%8E%E8%80%81%E5%B9%B4%E4%BB%A3"><span class="toc-text">年轻代与老年代</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%BE%E8%A7%A3%E5%AF%B9%E8%B1%A1%E5%88%86%E9%85%8D%E8%BF%87%E7%A8%8B"><span class="toc-text">图解对象分配过程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%BE%E8%A7%A3%E5%AF%B9%E8%B1%A1%E5%88%86%E9%85%8D%EF%BC%88%E4%B8%80%E8%88%AC%E6%83%85%E5%86%B5%EF%BC%89"><span class="toc-text">图解对象分配（一般情况）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E"><span class="toc-text">特殊情况说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E8%B0%83%E4%BC%98%E5%B7%A5%E5%85%B7"><span class="toc-text">常用调优工具</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#GC%E5%88%86%E7%B1%BB"><span class="toc-text">GC分类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Young-GC"><span class="toc-text">Young GC</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Major-Full-GC"><span class="toc-text">Major&#x2F;Full GC</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#GC%E6%97%A5%E5%BF%97%E5%88%86%E6%9E%90"><span class="toc-text">GC日志分析</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A0%86%E7%A9%BA%E9%97%B4%E5%88%86%E4%BB%A3%E6%80%9D%E6%83%B3"><span class="toc-text">堆空间分代思想</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D%E7%AD%96%E7%95%A5"><span class="toc-text">对象内存分配策略</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TLAB%E4%B8%BA%E5%AF%B9%E8%B1%A1%E5%88%86%E9%85%8D%E5%86%85%E5%AD%98%EF%BC%88%E4%BF%9D%E8%AF%81%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%EF%BC%89"><span class="toc-text">TLAB为对象分配内存（保证线程安全）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E6%9C%89-TLAB"><span class="toc-text">为什么有 TLAB</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF-TLAB"><span class="toc-text">什么是 TLAB</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#TLAB%E5%86%8D%E8%AF%B4%E6%98%8E"><span class="toc-text">TLAB再说明</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A0%86%E7%A9%BA%E9%97%B4%E5%8F%82%E6%95%B0%E8%AE%BE%E7%BD%AE"><span class="toc-text">堆空间参数设置</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E5%8F%82%E6%95%B0%E8%AE%BE%E7%BD%AE"><span class="toc-text">常用参数设置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%A9%BA%E9%97%B4%E5%88%86%E9%85%8D%E6%8B%85%E4%BF%9D"><span class="toc-text">空间分配担保</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A0%86%E6%98%AF%E5%88%86%E9%85%8D%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%94%AF%E4%B8%80%E9%80%89%E6%8B%A9%E4%B9%88%EF%BC%9F"><span class="toc-text">堆是分配对象的唯一选择么？</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%83%E9%80%B8%E5%88%86%E6%9E%90"><span class="toc-text">逃逸分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96"><span class="toc-text">代码优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%88%E4%B8%8A%E5%88%86%E9%85%8D"><span class="toc-text">栈上分配</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E7%9C%81%E7%95%A5%EF%BC%88%E5%90%8C%E6%AD%A5%E6%B6%88%E9%99%A4%EF%BC%89"><span class="toc-text">同步省略（同步消除）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%87%E9%87%8F%E6%9B%BF%E6%8D%A2"><span class="toc-text">标量替换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%83%E9%80%B8%E5%88%86%E6%9E%90%E7%9A%84%E4%B8%8D%E8%B6%B3"><span class="toc-text">逃逸分析的不足</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-text">小结</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>